package com.suo.enroll.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;

import com.aliyuncs.exceptions.ClientException;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import java.util.UUID;

public class OSSUtils {
    // 配置参数
    static final String bucket = "multi-compy";
    static final String accessKeyId = "LTAI5tNZbxEQFTXw6m7YmQFT";
    static final String accessKeySecret = "fKpMgcdZu10QiUkzG5DQHHrbPikqDH";
    static final String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    private static OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    // 上传文件并返回永久有效的URL
    public static String oss(MultipartFile image,Integer id) throws ClientException {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String originalFilename = image.getOriginalFilename();
        String filePath = "";
        try {
            //获取到文件名
            String originName= image.getOriginalFilename();
            //文件名
            String fileName = UUID.randomUUID().toString();
            //后缀
            String suffix=originName.substring(originName.lastIndexOf("."));
            //新文件名
            String newName=id + "_" + fileName+suffix;
            //完整路径
            String fileUrl = newName;
            //返回路径
            filePath="https://"+bucket+"."+endpoint+"/"+fileUrl;

            ossClient.putObject(bucket, newName, new ByteArrayInputStream(image.getBytes()));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        }
        catch (IOException e) {

        }
        finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return filePath;
    }

}
